import { useRouter } from "vue-router";
import mainStore from "@/store";
import { RouteRecordRaw } from "vue-router";

export default function commonHooks() {
   const router = useRouter();
   const store = mainStore();
   const routeAllPathToCompMap = import.meta.glob(`../views/**/*.vue`);

   function jumpUrl(path: string) {
      router.push(path);
   }

   /**
    * 添加路由信息
    */
   function addRoutes() {
      function value2Routers(tree: RouterConfig.Table[], parent?: RouterConfig.Table): RouteRecordRaw[] {
         let list: RouteRecordRaw[] = [];

         tree.forEach(item => {
            let children: RouteRecordRaw[] = [];

            if (item.children && item.children.length > 0) {
               children = value2Routers(item.children, item);
            }

            list.push({
               children: children || [],
               path: item.path,
               name: item.name || item.id,
               meta: {
                  label: item.meta_label,
                  icon: item.meta_icon
               },
               component: routeAllPathToCompMap[`../${item.component}`]
            });
         });

         return list;
      }

      const routers = value2Routers(store.router);

      let redirect_name: string | symbol | undefined;

      if (routers[0].children && routers[0].children.length > 0) {
         redirect_name = routers[0].children[0].name;
      }

      const main: RouteRecordRaw = {
         path: "/",
         name: "main",
         redirect: {
            name: redirect_name
         },
         children: [
            ...routers,
            {
               path: "",
               name: "404",
               component: () => import("@views/Layout/index.vue"),
               children: [
                  {
                     path: "/404",
                     component: () => import("@views/Common/404/index.vue")
                  }
               ]
            },
            {
               path: "/:pathMatch(.*)",
               redirect: "/404"
            }
         ]
      };

      router.addRoute(main);
   }

   return {
      jumpUrl,
      addRoutes
   };
}
